package com.cht.commonUtil.checkIn;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.cht.commonUtil.enums.CheckInStatus;
import com.cht.commonUtil.enums.MailType;
import com.cht.commonUtil.enums.RecipientType;
import com.cht.commonUtil.enums.Roles;
import com.cht.commonUtil.enums.ToDoType;
import com.cht.commonUtil.structure.ChkInRecord;
import com.cht.commonUtil.structure.ISR;
import com.cht.commonUtil.structure.ResultPack;
import com.cht.commonUtil.webInit.SP;
import com.cht.commonUtil.widgets.Widgets;
import com.google.gson.Gson;

public class CreateChkInRecord extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

		
		request.setCharacterEncoding( SP.UIcodeSet );
		response.setCharacterEncoding( SP.UIcodeSet );
		response.setContentType("application/json");
		
		
	    ChkInRecord cirj = new Gson().fromJson( request.getParameter("chkInRecordJson"), ChkInRecord.class);
		String empName = request.getParameter("empName");
		
	    String empId = cirj.getApplier();
	    
		String sql;
		ResultPack rp = new ResultPack(); 
		
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		
		
		try {
			conn = Widgets.getConn();
			String msgBody = "<font face='微軟正黑體'>您好,<p>"+cirj.getSubsysDesc()+"的&nbsp;"+empName+"&nbsp;提出了&nbsp;繳交原始碼予CM&nbsp;的申請!<p> ";	//信件內容
			
			msgBody += "原始碼來源："+cirj.getSvnIP()+cirj.getSvnPath()+"/<br>";
			msgBody += "版次："+cirj.getReversion()+"<P>";
			
			//建立LOG，第一步就開始記錄程式的執行
			sql="INSERT INTO changelog (changeLogId,changeTypeId,creatorId,bDate) VALUES (null,?,?,?)";
			ps = conn.prepareStatement(sql, new String[]{"changeLogId"} );
			ps.setInt(1, 11);
			ps.setString(2, empId);
			ps.setTimestamp(3, Widgets.cDT());
			ps.execute();
			rs = ps.getGeneratedKeys();
			rs.next();
			final int CHECK_IN_CHANGE_LOG_ID = rs.getInt(1);
			if ( ps !=null ) {ps.close();}
			if ( rs !=null ) { rs.close();}
			
			//新增繳交主檔	
			sql="INSERT INTO chkinmain (subsysId,chkInStatusId,isDailyBuild,svnOLurl,svnOLusr,svnOLver,creatorId,cDT,svnOriPath,apOriVer) VALUES (?,?,?,?,?,?,?,?,?,?)";
			ps = conn.prepareStatement(sql, new String[]{"chkInMainId"});
			ps.setString(1, cirj.getSubsysId() );
			ps.setInt(2, cirj.getStatus() );			//繳交記錄狀態
			ps.setString(3, cirj.isOL()?"f":"t" );		//是否為每日建置
			ps.setString(4, cirj.getSvnIP() );			
			ps.setString(5, cirj.getSvnID() );			
			ps.setInt(6, cirj.getReversion() );			
			ps.setString(7, empId );					//提交人員
			ps.setTimestamp(8, Widgets.cDT() );			//提交時間
			ps.setString(9, cirj.getSvnPath() );
			ps.setInt(10, cirj.getReversion() );			
			ps.execute();
			rs = ps.getGeneratedKeys();
			rs.next();
			final int CHECK_IN_ID = rs.getInt(1);
			
			ISR isr = cirj.getIsr();
			sql = "INSERT INTO isr8 (chkInId,stn,isQualified,comments) VALUES (?,?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, CHECK_IN_ID);
			//存入資安檢查報告
			for( int i=0; i< isr.getT8().size();i++ ) {
				ps.setInt(2,(i+1));
				ps.setString(3, isr.getT8().get(i).isB1()?"t":"f" );
				ps.setString(4, isr.getT8().get(i).getS1());
				ps.execute();
			}
			
			sql = "INSERT INTO isr9 (chkInId,stn,isQualified) VALUES (?,?,?)";
			ps = conn.prepareStatement(sql);
			ps.setInt(1, CHECK_IN_ID);
			//存入資安檢查報告
			for( int i=0; i< isr.getT9().size();i++ ) {
				ps.setInt(2,(i+1));
				ps.setString(3, isr.getT9().get(i)?"t":"f" );
				ps.execute();
			}
			
			
			String reqs = "<ul class='zhTwN req'>";
			//處理該模組需求
			for( int j=0; j < cirj.getReqs().size(); j++ ) {
				int reqId =  cirj.getReqs().get(j).getI1();	//需求ID
				reqs += "<li>"+cirj.getReqs().get(j).getS1()+"-"+cirj.getReqs().get(j).getS2()+"</li>";
				sql = "INSERT INTO mpChkinReq (chkInMainId,reqId) VALUES (?,?)";
				ps = conn.prepareStatement(sql);
				ps.setInt(1, CHECK_IN_ID);
				ps.setInt(2, reqId);
				ps.execute();
			}
			reqs += "</ul>";
			msgBody += "相關需求："+reqs+"<p><p>Best regards<br>"+empName+"</font><p><p>";
			
			//產生待辦事項
			Widgets.genToDoList(cirj.getSubsysId(), String.valueOf(CHECK_IN_ID), empId, ToDoType.REVIEWCHECKIN, Roles.MGR4PROGRAMMER);
			
			//將這筆變更申請目前的進度給修改
			//改變繳交的狀態  ==> 1 待審
			int chkInStatusId = CheckInStatus.APPROVING;
			Widgets.updateCHKINstatus(CHECK_IN_ID, chkInStatusId);
			
			//完成這次的異動
			sql = "UPDATE changelog SET eDate=? WHERE changeLogId=?";
			ps = conn.prepareStatement(sql);
			ps.setTimestamp(1, Widgets.cDT());
			ps.setInt(2, CHECK_IN_CHANGE_LOG_ID );
			ps.execute();
			
			//寄發通知信給AP主管
			//信件主旨
			List<String[]> tos = Widgets.getRecipient( MailType.APPLY_CHKIN,RecipientType.TO,cirj.getSubsysId() );
			List<String[]> ccs = Widgets.getRecipient( MailType.APPLY_CHKIN,RecipientType.CC,cirj.getSubsysId());
			List<String[]> bccs = Widgets.getRecipient( MailType.APPLY_CHKIN,RecipientType.BCC,cirj.getSubsysId());
			String subject = cirj.getSubsysDesc()+"-繳交申請-"+CHECK_IN_ID;
			Widgets.sendMailMain(tos,ccs,bccs,subject, msgBody);
		
			rp.setSuccess(true);
		} catch(Exception e) {
			rp = Widgets.setResultPack(rp, e);
			Widgets.errLog(e);
		} finally {
			try {
				if ( rs !=null ) {rs.close();}
				if ( ps !=null ) {ps.close();}
				if ( conn !=null ) {conn.close();}	
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	    
	    response.getWriter().write( new Gson().toJson(rp) );
	
	}

}
